package ynu.edu.online_course.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.online_course.entity.Banned;
import ynu.edu.online_course.entity.User;
import ynu.edu.online_course.service.UserService;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String telephone, @RequestParam String password) {
        Long UserId = userService.login(telephone, password);
        if (UserId != null) {
            return ResponseEntity.ok("用户uid为"+UserId.toString());
        }
        return ResponseEntity.status(401).body("账户或密码错误");
    }


    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        if(userService.register(user)) {
            userService.register(user);
            return ResponseEntity.ok("用户注册成功");
        }
        else
            return ResponseEntity.status(401).body("该号码已被注册");
    }

    @PutMapping("/{id}/password")
    public ResponseEntity<?> updatePassword(@PathVariable Long id, @RequestBody String newPassword) {
        try {
            userService.updatePassword(id, newPassword);
            return ResponseEntity.ok("密码修改成功");
        } catch (RuntimeException e) {
            return ResponseEntity.status(400).body(e.getMessage());
        }
    }

    @PutMapping("/{id}/telephone")
    public ResponseEntity<?> updateTelephone(@PathVariable Long id, @RequestBody String newTelephone) {
        try {
            userService.updateTelephone(id, newTelephone);
            return ResponseEntity.ok("号码修改成功");
        } catch (RuntimeException e) {
            return ResponseEntity.status(400).body("号码修改失败");
        }
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.ok("用户已注销");
    }

    @DeleteMapping("/ban")
    public ResponseEntity<?> banUser(@RequestBody Banned banned) {
        if (banned.getUser() == null || banned.getUser().getId() == null) {
            return ResponseEntity.badRequest().body("需要用户ID");
        }
        userService.banUser(banned);
        return ResponseEntity.ok("用户已封禁");
    }


}
